; irq.asm
; interrupt request routine for vertical retrace synchronization
;

	.include "global.inc"
	.include "vicrom.inc"
	.include "sound.inc"
	
	.export initirq
	.export execirq
	.export waitframe

	.segment "DATA"
	
vsync_flg:	.byte 0
tps:		.byte 0

	.segment "CODE"
	
initirq:	lda #0
			sta vsync_flg
			lda MACHINE			; machine detection by r.hurst
			cmp #M_NTSC
			beq @ntsc
			cmp #M_PAL
			beq @pal
			; TODO: what next?
@ntsc:		lda #NTSC_TPS
			sta tps
			lda #<NTSC_TIMER_VALUE
			sta $9124
			ldx #>NTSC_TIMER_VALUE
			lda #NTSC_LINE
			bne irqsync
@pal:		lda #PAL_TPS
			sta tps
			lda #<PAL_TIMER_VALUE
			sta $9124
			ldx #>PAL_TIMER_VALUE
			lda #PAL_LINE
			bne irqsync
irqsync:	cmp VIC_BASE+$04
			bne irqsync
			stx $9125		; load T1 latch high, and transfer both bytes to T1 counter
			rts

execirq:	lda vsync_flg
			beq @done_sync
			dec vsync_flg
@done_sync: rts

waitframe:	; wait for vertical retrace
			lda #1
			sta vsync_flg
@pollwait:	cmp vsync_flg
			beq @pollwait
			rts

